

#include <stdio.h>
#include <stdlib.h>

struct ListNode{
    int val;
    struct ListNode *next;
};

typedef struct ListNode Node, *pNode;

void print(struct ListNode* p)
{
	struct ListNode* q;
	for(q = p; q != NULL; q = q->next)
		printf("[%d]", q->val);
	printf("\n");
}

void setList(struct ListNode * p, int val)
{
	struct ListNode *q;
	q = p;
	while(q->next != NULL)
		q = q->next;
	
	struct ListNode *tmp = (struct ListNode *)malloc(sizeof(struct ListNode));
	if(tmp == NULL)
		return;
	tmp->val = val;
	tmp->next = q->next;
	q->next = tmp;
}

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    int i, len;
	struct ListNode* p, *q;
	struct ListNode* result;
	p = head;
	len = 1;
	result = (struct ListNode *)malloc(sizeof(struct ListNode));
	if(NULL == result)
		return NULL;
	
	while(p->next != NULL)
	{	
		p = p->next;
		len++;
	}
	q = p = head;
	for(i = 0; i < len-n; i++)
	{
		q = p;
		p = p->next;
	}
	if(p == head && p->next == NULL)
		head = NULL;
	else if(p == head)
	{
		head = head->next;
	}
	else
	{
		q->next = p->next;	
	}
	free(p);
	return head;
}

int main(void)
{
	struct ListNode* head;
	int num[] = {1,2};
	int val = 1;
	int i;
	head = (struct ListNode *)malloc(sizeof(struct ListNode));
	head->val = num[0];
	head->next = NULL;
	for(i = 1; i < sizeof(num)/sizeof(int); i++)
		setList(head, num[i]);
	print(head);
	print(removeNthFromEnd(head, val));
	return 0;
}